/*
 * @Author: yangzonglong
 * @Date: 2020-05-27 10:25:06
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: juwenzheng 3225460988@qq.com
 * @LastEditTime: 2022-05-13 16:43:25
 * @Auditor: 
 */
import { CancelTokenSource } from 'axios';
import server from '@library/utils/server/server';
import ApiQuery from '@library/interface/apiQuery';
import { PlanLocationProps } from './PlantLocation';

interface GetListOprions {
  url: string;
  page: number;
  pageSize: number;
  query?: object;
}

export async function getList({ url, page, pageSize, query }: GetListOprions, source: CancelTokenSource) {
  try {

    const data: ApiQuery = { ...query, pages: { pageSize, page } };

    const result = await server(url, data, { cancelToken: source.token });
    const rows = Array.isArray(result) ? result : (result.rows || []);

    return {
      count: result.count || rows.length,
      rows: rows.map((item: any) => ({ ...item, _page: page }))
    };
  } catch (error) {
    return { count: 0, rows: [] };
  }
}

let inRequest = false; // 标记正在请求
let callbacks: Function[] = [];
let cachePlantLocations: PlanLocationProps[] | null = null;

// 获取工厂库位
export async function getPlantLocation(callback: Function) {

  if (inRequest) {
    if (cachePlantLocations) return callback(cachePlantLocations);
    return callbacks.push(callback);
  }

  callbacks.push(callback);
  inRequest = true;

  const { rows } = await server('/bk/api/warehouse/StorageLocation/find', {});

  const data: PlanLocationProps[] = [];

  rows.forEach((item: Record<string, any>) => {
    if (!data.length) {
      data.push({ label: item.plantName!, value: item.plantCode!, children: [] });
    }

    if (!data.find(plant => plant.value === item.plantCode)) {
      data.push({ label: item.plantName!, value: item.plantCode!, children: [] });
    }

    data.find(plant => plant.value === item.plantCode)?.children.push({
      label: item.storageLocationName!,
      value: item.storageLocationCode!,
      binFlag: item.binFlag
    });
  });

  callbacks.forEach(fn => fn(data));
  callbacks = [];
  cachePlantLocations = data;
}